<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户名称">
                <a-input v-model:value="queryParam.userName" allow-clear placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号码">
                <a-input v-model:value="queryParam.phonenumber" allow-clear placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="handleQuery">
                  <BearJiaIcon type="search"/>查询
                </a-button>
                <a-button style="margin-left: 8px" @click="resetQuery">
                  <BearJiaIcon type="redo"/>重置
                </a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 操作 -->
      <div class="table-operations">
        <a-button v-has-permi="['system:role:add']" type="primary" @click="selectUserRef.handleAuthUser()">
          <BearJiaIcon type="plus"/>
          添加用户
        </a-button>
        <a-button
            v-has-permi="['system:role:remove']"
            :disabled="multiple"
            :loading="authing"
            type="danger"
            @click="cancelAuthUserAll"
        >
          <BearJiaIcon type="delete"/>
          取消批量授权
        </a-button>
        <a-button type="primary" @click="back">
          <BearJiaIcon type="edit"/>
          返回
        </a-button>
        <table-setting
            v-model="columns"
            v-model:table-size="tableSize"
            :refresh-loading="loading"
            :style="{ float: 'right' }"
            @refresh="getList"
        />
      </div>
      <select-user
          ref="selectUserRef"
          :role-id="queryParam.roleId"
          :status-options="dict.type['sys_normal_disable']"
          @ok="getList"
      />
      <!-- 数据展示 -->
      <a-table
          :columns="columns"
          :data-source="list"
          :loading="loading"
          :pagination="false"
          :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
          row-key="userId"
      >
        <template #status="{ record }">
          <index :options="dict.type['sys_normal_disable']" :value="record.status"/>
        </template>
        <template #createTime="{ record }">
          {{ parseTime(record.createTime) }}
        </template>
        <template #operation="{ record }">
          <a v-has-permi="['system:role:remove']" @click="cancelAuthUser(record)">
            <BearJiaIcon icon="edit"/>
            取消授权
          </a>
        </template>
      </a-table>
      <!-- 分页 -->
      <a-pagination
          :current="queryParam.pageNum"
          :page-size="queryParam.pageSize"
          :show-total="total => `共 ${total} 条`"
          :total="total"
          class="ant-table-pagination"
          show-quick-jumper
          show-size-changer
          @change="changeSize"
          @showSizeChange="onShowSizeChange"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {allocatedUserList, authUserCancel, authUserCancelAll} from '@/api/system/role';
import SelectUser from './modules/SelectUser.vue';
import {message, Modal} from 'ant-design-vue';
import Index from '@components/DictTag/index.vue'; // 假设已调整为 Vue 3 兼容

// 字典数据（假设从全局注入或外部获取）
const dict = {
  type: {
    sys_normal_disable: [
      {value: '0', label: '正常'},
      {value: '1', label: '禁用'},
    ],
  },
};

// 路由
const route = useRoute();
const router = useRouter();

// 表格相关状态
const list = ref([]);
const selectedRowKeys = ref([]);
const selectedRows = ref([]);
const single = ref(true);
const multiple = ref(true);
const ids = ref([]);
const loading = ref(false);
const authing = ref(false);
const total = ref(0);
const tableSize = ref('middle');
const tableBordered = ref(false);

// 查询参数
const queryParam = reactive({
  pageNum: 1,
  pageSize: 10,
  roleId: '',
  userName: undefined,
  phonenumber: undefined,
});

// 表格列定义
const columns = ref([
  {title: '用户名称', dataIndex: 'userName', align: 'center'},
  {title: '用户昵称', dataIndex: 'nickName', ellipsis: true, align: 'center'},
  {title: '邮箱', dataIndex: 'email', ellipsis: true, align: 'center'},
  {title: '手机', dataIndex: 'phonenumber', align: 'center'},
  {title: '状态', dataIndex: 'status', slots: {customRender: 'status'}, align: 'center'},
  {title: '创建时间', dataIndex: 'createTime', slots: {customRender: 'createTime'}, align: 'center'},
  {title: '操作', dataIndex: 'operation', width: '20%', slots: {customRender: 'operation'}, align: 'center'},
]);

// 组件引用
const selectUserRef = ref();

// 时间格式化函数（从 tableMixin 中提取）
const parseTime = (time) => {
  return time ? new Date(time).toLocaleString() : '';
};

// 查询授权用户列表
const getList = () => {
  loading.value = true;
  allocatedUserList(queryParam).then((response) => {
    list.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

// 搜索按钮操作
const handleQuery = () => {
  queryParam.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryParam.pageNum = 1;
  queryParam.pageSize = 10;
  queryParam.userName = undefined;
  queryParam.phonenumber = undefined;
  handleQuery();
};

// 分页大小改变
const onShowSizeChange = (current, pageSize) => {
  queryParam.pageSize = pageSize;
  getList();
};

// 分页切换
const changeSize = (current, pageSize) => {
  queryParam.pageNum = current;
  queryParam.pageSize = pageSize;
  getList();
};

// 表格行选择
const onSelectChange = (keys, rows) => {
  selectedRowKeys.value = keys;
  selectedRows.value = rows;
  ids.value = rows.map((item) => item.userId);
  single.value = keys.length !== 1;
  multiple.value = !keys.length;
};

// 取消授权
const cancelAuthUser = (record) => {
  Modal.confirm({
    title: '确认要取消该用户的角色吗?',
    content: `当前选中用户 ${record.userName}`,
    onOk() {
      const param = {
        userId: record.userId,
        roleId: queryParam.roleId,
      };
      return authUserCancel(param).then(() => {
        onSelectChange([], []);
        getList();
        message.success('取消授权成功');
      });
    },
  });
};

// 批量取消授权
const cancelAuthUserAll = () => {
  Modal.confirm({
    title: '是否取消选中用户授权数据项?',
    onOk() {
      const param = {
        roleId: queryParam.roleId,
        userIds: ids.value,
      };
      authing.value = true;
      return authUserCancelAll(param)
          .then(() => {
            onSelectChange([], []);
            getList();
            message.success('取消授权成功');
          })
          .finally(() => {
            authing.value = false;
          });
    },
  });
};

// 返回
const back = () => {
  router.push({path: '/system/role'});
};

// 初始化
onMounted(() => {
  const roleId = route.query?.roleId;
  if (roleId) {
    queryParam.roleId = roleId;
    getList();
  }
});
</script>

<style scoped>
/* 如果需要样式，可以在这里定义 */
.table-page-search-wrapper {
  margin-bottom: 16px;
}

.table-operations {
  margin-bottom: 16px;
}

.ant-table-pagination {
  margin-top: 16px;
}
</style>